package com.example.ross.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.ross.common.Result;
import com.example.ross.form.UserForm;
import com.example.ross.security.LoginUser;
import com.example.ross.service.LoginService;
import com.example.ross.utils.JwtUtil;
import com.example.ross.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @className: LoginServiceImpl
 * @description:
 * @author: zhangjunfa
 * @date: 2023/5/6 18:24
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     *
     * @param userForm
     * @return
     */
    @Override
    public Map<String, String> login(UserForm userForm) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userForm.getUserName(), userForm.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisUtil.setEx("login:" + userId, loginUser, 10000, TimeUnit.SECONDS);
        //把token响应给前端
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }

    /**
     * 用户退出
     *
     * @return
     */
    @Override
    public void logout() {

    }
}
